package xyz.eden.cloud.track.tus.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.desair.tus.server.TusFileUploadService;
import me.desair.tus.server.upload.UploadInfo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import xyz.eden.cloud.track.tus.service.ITusService;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.Objects;

@Slf4j
@Service
public class TusServiceImpl implements ITusService {

    @Resource
    private TusFileUploadService tusFileUploadService;
    @Value("${tus.base.url}")
    private String tusServerURL;


    @Override
    public String getImageFileDataBase64(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }

        try {
            String url = tusServerURL + "/" + filePath;
            UploadInfo info = tusFileUploadService.getUploadInfo(url);
            if (Objects.isNull(info)) {
                log.info("getFileDataBase64 - filePath: [{}] 获取 UploadInfo 为空.", filePath);
                return null;
            }
            MediaType mediaType = MediaTypeFactory.getMediaType(info.getFileName()).orElse(null);
            String type = Objects.isNull(mediaType) ? null : mediaType.getType();
            if (StringUtils.isBlank(type)) {
                log.info("getFileDataBase64 - 通过 fileName: [{}] 获取类型为空.", info.getFileName());
                return null;
            }
            InputStream inputStream = tusFileUploadService.getUploadedBytes(url);
            if (Objects.isNull(inputStream)) {
                log.info("getFileDataBase64 - filePath: [{}] 获取 InputStream 为空.", filePath);
                return null;
            }
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, output);
            String str = "data:" + type + ";base64,";
            Base64.Encoder encoder = Base64.getEncoder();
            return str + encoder.encodeToString(output.toByteArray());
        } catch (Exception e) {
            log.error("getFileDataBase64 - 获取图片 base64 编码出现异常.", e);
            return null;
        }
    }
}
